
package java.util.concurrent.locks;
import java.util.concurrent.TimeUnit;

public class ReentrantLock extends AbstractQueuedSynchronizer implements Lock, java.io.Serializable {
    private static final long serialVersionUID = 7373984872572414699L;

    //唯一一个属性
    private final Sync sync;

    //他有两个实现类：都在当前类里面，一个是公平锁的逻辑，一个是非公平锁的逻辑。
    //他继承了AQS来实现重入锁的逻辑，但是AQS本身不具备业务功能，所以在不同的同步场景，
    //会继承AQS来实现对应场景的功能。
    abstract static class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = -5179523762034025860L;

        abstract void lock();

        final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                if (compareAndSetState(0, acquires)) {//CAS修改state
                    setExclusiveOwnerThread(current);
                    return true;
                }
            } else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;//计算重入后的state
                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }

        //这个方法可以认为是一个释放锁状态的操作，
        //其实这个方法在排他锁和共享锁下是有点不一样的..
        protected final boolean tryRelease(int releases) {
            //将当前值与传入的值进行相减
            int c = getState() - releases;//计算释放后的state值
            //如果当前线程不是持有锁的线程，抛出非法同步状态异常
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            //表示是否完全释放锁成功
            boolean free = false;
            //表示重入锁已经完全释放
            if (c == 0) {
                free = true;//锁全部释放，可以唤醒下一个等待线程
                setExclusiveOwnerThread(null);//设置锁持有线程为null
            }
            //修改state状态
            setState(c);
            return free;
        }

        protected final boolean isHeldExclusively() {
            return getExclusiveOwnerThread() == Thread.currentThread();
        }

        final ConditionObject newCondition() {
            //实际上创建了一个AQS的内部对象
            return new ConditionObject();
        }

        // Methods relayed from outer class

        final Thread getOwner() {
            return getState() == 0 ? null : getExclusiveOwnerThread();
        }

        final int getHoldCount() {
            return isHeldExclusively() ? getState() : 0;
        }

        final boolean isLocked() {
            return getState() != 0;
        }

        private void readObject(java.io.ObjectInputStream s)
            throws java.io.IOException, ClassNotFoundException {
            s.defaultReadObject();
            setState(0); // reset to unlocked state
        }
    }

    //非公平锁的逻辑
    static final class NonfairSync extends Sync {
        private static final long serialVersionUID = 7316153563782823691L;

        //非公平锁获取
        final void lock() {
            //首先去cas的方式尝试获取锁
            if (compareAndSetState(0, 1))
                //获取成功就把当前持有锁的线程改成自己
                setExclusiveOwnerThread(Thread.currentThread());
            else
                //获取锁失败就走竞争锁的逻辑
                acquire(1);
        }

        //非公平锁获取
        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
    }

    //公平锁
    static final class FairSync extends Sync {
        private static final long serialVersionUID = -3000897897090466540L;

        //公平锁获取
        final void lock() {
            //这里直接调用了aqs的方法去竞争锁
            acquire(1);
        }

        protected final boolean tryAcquire(int acquires) {
            //获取当前线程
            final Thread current = Thread.currentThread();
            int c = getState();//获取锁状态state
            //条件成立：说明当前是无锁状态
            if (c == 0) {
                if (!hasQueuedPredecessors() && //判断当前线程是否还有前节点
                    compareAndSetState(0, acquires)) {//CAS修改state

                    //什么时候条件成立？
                    //当前线程没有前驱节点，cas更新state字段成功

                    //此时一定是获取锁成功，设置锁的持有线程为当前线程
                    setExclusiveOwnerThread(current);

                    return true;
                }
            }
            //这里是锁重入的逻辑，重入的话就直接在state上继续累加即可。
            else if (current == getExclusiveOwnerThread()) {//当前线程已经持有锁
                int nextc = c + acquires;//重入
                if (nextc < 0)
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);//更新state状态，这里为什么没加锁？
                //因为当前是锁重入的逻辑，当前线程就是持有锁的线程，本次操作是线程安全的，无需加锁。
                return true;
            }
            //什么时候走到这里？
            //1.当前线程所在节点有前驱节点，且前驱节点不是自己
            //2.当前线程没有前驱节点，但是cas获取锁失败了，（在当前线程cas的时候有其他线程抢先一步了）
            return false;
        }
    }

    public ReentrantLock() {
        //默认是非公平锁
        sync = new NonfairSync();
    }

    public ReentrantLock(boolean fair) {
        //手动指定是否是公平锁
        sync = fair ? new FairSync() : new NonfairSync();
    }

    //获取锁，一直等待锁可用
    public void lock() {
        //直接调用了 sync的lock方法
        sync.lock();
    }

    //响应中断的加锁逻辑
    public void lockInterruptibly() throws InterruptedException {
        //这里其实又调用到了aqs
        sync.acquireInterruptibly(1);
    }

    public boolean tryLock() {
        return sync.nonfairTryAcquire(1);
    }

    public boolean tryLock(long timeout, TimeUnit unit)
            throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(timeout));
    }

    //释放锁
    public void unlock() {
        //执行sync的release，默认是非公平锁
        sync.release(1);
    }


    //创建一个等待条件
    public Condition newCondition() {
        return sync.newCondition();
    }




    public int getHoldCount() {
        return sync.getHoldCount();
    }

    public boolean isHeldByCurrentThread() {
        return sync.isHeldExclusively();
    }

    public boolean isLocked() {
        return sync.isLocked();
    }

    public final boolean isFair() {
        return sync instanceof FairSync;
    }

    public String toString() {
        Thread o = sync.getOwner();
        return super.toString() + ((o == null) ?
                                   "[Unlocked]" :
                                   "[Locked by thread " + o.getName() + "]");
    }
}
